import { defineStore } from 'pinia'
/**
 * @file 边栏标签页状态管理
 * @description 专门管理边栏标签页的状态和操作，与普通标签页分离
 * @author 黄敏
 * @version 1.0.0
 * @since 2025-07-13
 */
import { computed, reactive } from 'vue'

import { TAB_IDS } from '~shared/constants'
import { SYSTEM_TABS } from '~shared/constants/tab'
import {
  createBrowserTabFromPersistData,
  createOriginTab,
  generateSidebarTabId
} from '@/utils/tab-factory'
import { TabOperationsManager } from '@/utils/tab-operations'
// 导入工具函数
import {
  loadTabsFromStorage,
  saveTabsToStorage,
  STORAGE_KEYS,
  type StorageKey,
  updateSidebarTabs
} from '@/utils/tab-storage'
import { layoutOn } from '@/utils/layoutEvent'

export const defaultLeftSystemTabs = [
  SYSTEM_TABS[TAB_IDS.ACCOUNT],
  SYSTEM_TABS[TAB_IDS.CALENDAR],
  SYSTEM_TABS[TAB_IDS.MAIL]
]

export const defaultRightSystemTabs = [
  SYSTEM_TABS[TAB_IDS.SEARCH],
  SYSTEM_TABS[TAB_IDS.CAMPAIGN],
  SYSTEM_TABS[TAB_IDS.TASK],
  SYSTEM_TABS[TAB_IDS.ACTIVITY]
]

/**
 * 从 localStorage 加载边栏标签页并转换为 F2.tab.Sidebar 格式
 */
function loadSidebarTabsFromStorage(key: StorageKey): F2.tab.Sidebar[] {
  try {
    let persistedTabs = loadTabsFromStorage(key)
    let tabs: F2.tab.Entity[] = []

    if (key === STORAGE_KEYS.LEFT_SIDEBAR) {
      tabs = _pre_.browser.getLeftTabs()
    } else if (key === STORAGE_KEYS.RIGHT_SIDEBAR) {
      tabs = _pre_.browser.getRightTabs()
    }

    if (!persistedTabs) {
      // 没有缓存数据，则使用默认值
      if (key === STORAGE_KEYS.LEFT_SIDEBAR) {
        persistedTabs = defaultLeftSystemTabs.map(tab => createOriginTab(tab))
        persistedTabs = persistedTabs.concat(tabs.map(tab => createOriginTab(tab)))
      } else if (key === STORAGE_KEYS.RIGHT_SIDEBAR) {
        persistedTabs = defaultRightSystemTabs.map(tab => createOriginTab(tab))
      } else {
        persistedTabs = []
      }
    }
    // 将持久化数据转换为完整的 BrowserTab 对象
    return persistedTabs.map(persistedTab => ({
      origin: persistedTab,
      data: tabs.find(t => t.id === persistedTab.id) || null
    }))
  } catch (error) {
    console.error('加载边栏标签页失败:', error)
    return []
  }
}

/**
 * 边栏标签页状态管理
 */
export const useSidebarStore = defineStore('sidebar', () => {
  const isMainWindow = _pre_.browser.isMainWindow()
  const data: {
    leftTabs: F2.tab.Sidebar[] // 左侧边栏标签页
    rightTabs: F2.tab.Sidebar[] // 右侧边栏标签页
    rightTempTabs: F2.tab.Entity[] // 右侧边栏临时标签页
    rightActiveIds: number[] // 右侧边栏活动标签页ID
    activeId: number // 当前活动标签页ID,请不要直接修改
    separateOpenIds: number[] // 当前独立窗口打开的标签页ID
  } = reactive({
    leftTabs: isMainWindow ? loadSidebarTabsFromStorage(STORAGE_KEYS.LEFT_SIDEBAR) : [],
    rightTabs: loadSidebarTabsFromStorage(STORAGE_KEYS.RIGHT_SIDEBAR),
    rightTempTabs: [] as F2.tab.Entity[],
    separateOpenIds: _pre_.browser.getSeparateOpenIds(),
    rightActiveIds: [] as number[], // 当前右侧边栏活动标签页ID,请不要直接修改
    activeId: 0
  })

  layoutOn('open-separate-windows:change', ids => {
    data.separateOpenIds = ids
  })

  layoutOn('left:update', ts => {
    updateSidebarTabs(data.leftTabs, ts, STORAGE_KEYS.LEFT_SIDEBAR)
  })

  layoutOn('right:update', ts => {
    const isUpdate = updateSidebarTabs(data.rightTabs, ts, STORAGE_KEYS.RIGHT_SIDEBAR)
    if (!isUpdate) {
      const right = findRightTempTab(ts.id)
      if (right) {
        Object.assign(right, ts)
      }
    }
  })

  layoutOn('right:switch', id => {
    data.rightActiveIds = id
  })

  layoutOn('right:created', bros => {
    console.log('rightTab', bros)

    for (const b of bros) {
      const rightTab = findRightTab(b.id)
      if (rightTab) {
        rightTab.data = b
      } else if (!findRightTempTab(b.id)) {
        data.rightTempTabs.push(b)
      }
    }
  })

  layoutOn('left:created', bros => {
    for (const b of bros) {
      const rightTab = findLeftTab(b.id)
      if (rightTab) {
        rightTab.data = b
      }
    }
  })

  layoutOn('left:close', tabIds => {
    for (const id of tabIds) {
      const rightTab = findLeftTab(id)
      if (rightTab) {
        rightTab.data = null
      }
    }
  })

  layoutOn('right:close', tabIds => {
    for (const id of tabIds) {
      const rightTab = findRightTab(id)
      if (rightTab) {
        rightTab.data = null
      } else {
        const i = data.rightTempTabs.findIndex(t => t.id === id)
        if (i !== -1) {
          data.rightTempTabs.splice(i, 1)
        }
      }
    }
  })

  // 预打开参数为autoOpenOnStartup: true 的标签页
  const autoLeftTabs = data.leftTabs
    .filter(v => v.origin.autoOpenOnStartup)
    .map(v => createBrowserTabFromPersistData(v.origin))

  if (autoLeftTabs.length > 0) {
    _pre_.browser.addTab(autoLeftTabs, 'left')
  }

  const autoRIghtTabs = data.rightTabs
    .filter(v => v.origin.autoOpenOnStartup)
    .map(v => createBrowserTabFromPersistData(v.origin))
  if (autoRIghtTabs.length > 0) {
    _pre_.browser.addTab(autoRIghtTabs, 'right')
  }

  const currentSidebars = computed(() => {
    return data.rightActiveIds
      .map(id => findRightTempTab(id) || findRightTab(id)?.data)
      .filter(Boolean) as F2.tab.Entity[]
  })

  /**
   * 添加边栏标签页
   */
  function addSidebarTab(tabData: F2.tab.Create, isRight?: boolean, insertIndex?: number) {
    const tabs = isRight ? data.rightTabs : data.leftTabs

    const newTab: F2.tab.PersistData = createOriginTab(tabData)

    // 添加到边栏标签页列表
    if (typeof insertIndex === 'number') {
      tabs.splice(insertIndex, 0, { data: null, origin: newTab })
    } else {
      tabs.push({ data: null, origin: newTab })
    }

    const browerTab = createBrowserTabFromPersistData(newTab)

    // 通过 _pre_.tab 创建实际的标签页，只传递必要参数
    _pre_.browser.addTab(browerTab, isRight ? 'right' : 'left')

    // 保存到 localStorage
    saveTabsToStorage(tabs, isRight ? STORAGE_KEYS.RIGHT_SIDEBAR : STORAGE_KEYS.LEFT_SIDEBAR)

    return browerTab
  }

  /**
   * 删除边栏标签页
   */
  function removeLeftTab(tabId: number) {
    // 检查是否是当前活动标签页，如果是则需要切换到其他标签页
    if (data.activeId === tabId) {
      const allLeftTabs = data.leftTabs.map(s => s.origin)
      const nextActiveTabId = TabOperationsManager.getNextActiveTabId(
        data.activeId,
        [tabId],
        allLeftTabs
      )

      if (nextActiveTabId && nextActiveTabId !== tabId) {
        setActiveTab(nextActiveTabId, 'left')
      }
    }

    // 从边栏标签页列表中移除
    data.leftTabs = data.leftTabs.filter(sidebar => sidebar.origin.id !== tabId)

    // 保存到 localStorage
    saveTabsToStorage(data.leftTabs, STORAGE_KEYS.LEFT_SIDEBAR)

    // 通过 _pre_.tab 关闭实际的标签页
    _pre_.browser.closeTabs([tabId])
  }

  /**
   * 移动边栏标签页顺序
   * @param fromIndex 源位置索引
   * @param toIndex 目标位置索引
   * @param isRight 是否为右侧边栏
   */
  function moveSidebarTab(fromIndex: number, toIndex: number, isRight?: boolean): void {
    const tabs = isRight ? data.rightTabs : data.leftTabs
    if (
      fromIndex < 0 ||
      toIndex < 0 ||
      fromIndex >= tabs.length ||
      toIndex >= tabs.length ||
      fromIndex === toIndex
    ) {
      return
    }

    // 移动数组中的元素
    const [movedTab] = tabs.splice(fromIndex, 1)
    if (movedTab) {
      tabs.splice(toIndex, 0, movedTab)
    }

    // 保存到 localStorage
    saveTabsToStorage(tabs, isRight ? STORAGE_KEYS.RIGHT_SIDEBAR : STORAGE_KEYS.LEFT_SIDEBAR)
  }

  /**
   * 跨侧边栏移动标签页
   * @param tabId 要移动的标签页ID
   * @param toRight 目标是否为右侧边栏（true 表示移动到右侧）
   * @param toIndex 在目标侧边栏中的插入索引（允许等于目标长度，表示追加到末尾）
   */
  function moveSidebarTabAcrossSides(tabId: number, toRight: boolean, toIndex: number): void {
    const sourceTabs = toRight ? data.leftTabs : data.rightTabs
    const targetTabs = toRight ? data.rightTabs : data.leftTabs

    const fromTab = sourceTabs.find(s => s.origin.id === tabId)
    if (!fromTab) return
    const origin = JSON.parse(JSON.stringify(fromTab.origin))
    // 规范化插入位置
    let insertIndex = toIndex
    if (insertIndex < 0) insertIndex = 0
    if (insertIndex > targetTabs.length) insertIndex = targetTabs.length

    if (toRight) {
      removeLeftTab(fromTab.origin.id)
    } else {
      removeRightTab(fromTab.origin.id)
      origin.isInSeparateWindow = false
      origin.isPinned = false
      origin.isMobile = false
    }

    nextTick(() => {
      addSidebarTab(origin, toRight, insertIndex)
    })
  }

  /**
   * 根据ID查找边栏标签页
   */
  function findLeftTab(tabId: number): F2.tab.Sidebar | undefined {
    return data.leftTabs.find(sidebar => sidebar.origin.id === tabId)
  }

  function findRightTab(tabId: number): F2.tab.Sidebar | undefined {
    return data.rightTabs.find(sidebar => sidebar.origin.id === tabId)
  }

  function findRightTempTab(tabId: number): F2.tab.Entity | undefined {
    return data.rightTempTabs.find(sidebar => sidebar.id === tabId)
  }

  /**
   * 检查是否为边栏标签页
   */
  const leftIds = computed(() => data.leftTabs.map(s => s.origin.id))

  function isLeftTab(tabId: number): boolean {
    return leftIds.value.includes(tabId)
  }

  const rightIds = computed(() => data.rightTabs.map(s => s.origin.id))

  function isRightTab(tabId: number): boolean {
    return rightIds.value.includes(tabId)
  }

  /**
   * 记录左侧边栏标签页最后一个活动标签页ID
   * */

  const lastLeftActiveTabId = ref(
    data.leftTabs.find(v => !v.origin.isInSeparateWindow)?.origin.id ?? 0
  )
  layoutOn('switch', id => {
    data.activeId = id
    if (id && isLeftTab(id)) {
      lastLeftActiveTabId.value = id
    }
  })

  /**
   * 删除右边栏标签页
   * @param tabId 要删除的标签页ID
   */
  function removeRightTab(tabId: number) {
    if (findRightTempTab(tabId)) {
      // 从临时标签页列表中移除
      data.rightTempTabs = data.rightTempTabs.filter(sidebar => sidebar.id !== tabId)
    } else if (findRightTab(tabId)) {
      // 从右边栏标签页列表中移除
      data.rightTabs = data.rightTabs.filter(sidebar => sidebar.origin.id !== tabId)

      // 保存到 localStorage
      saveTabsToStorage(data.rightTabs, STORAGE_KEYS.RIGHT_SIDEBAR)
    }

    // 通过 _pre_.sidebar 关闭实际的标签页
    _pre_.browser.closeTabs([tabId])
  }

  /**
   * 设置活动标签页
   * @param tabId 要设置的标签页ID
   * @param type 标签页类型 (left: 左侧边栏, right: 右侧边栏)
   */
  function setActiveTab(tabId: number, type: 'left' | 'right') {
    if (
      data.separateOpenIds.includes(tabId) ||
      (type === 'right' && data.rightActiveIds.includes(tabId))
    ) {
      _pre_.browser.hideTab(tabId)
      return
    }
    const tempTab = findRightTempTab(tabId)
    if (tempTab) {
      _pre_.browser.setActiveTab(tempTab.id)
      return
    }
    const tabs = type === 'left' ? data.leftTabs : data.rightTabs
    const tab = tabs.find(t => t.origin.id === tabId)

    if (!tab) return

    if (tab.data) {
      _pre_.browser.setActiveTab(tabId)
    } else {
      const addTab = createBrowserTabFromPersistData(tab.origin)
      addTab.autoFocus = true // 设置自动获取焦点
      _pre_.browser.addTab(addTab, type)
    }
  }

  /**
   * 打右侧栏打开临时标签页
   * */
  function openRightTempTab(tabParam: F2.tab.Create) {
    _pre_.browser.addTab(tabParam, 'right')
  }

  /**
   * 将顶部标签页移动到指定侧边栏
   * @param tab 要移动的标签页
   * @param isRight 是否移动到右侧边栏
   * @param insertIndex 移动到的索引位置
   */
  const moveTabToSidebar = (tab: F2.tab.Entity, isRight?: boolean, insertIndex?: number) => {
    const sideText = isRight ? '右侧' : '左侧'

    try {
      // 创建标签页数据
      const tabData = {
        id: tab.id < 0 ? tab.id : generateSidebarTabId(),
        url: tab.url,
        title: tab.title,
        favicon: tab.favicon,
        icon: tab.icon
      }

      // 根据侧边栏位置调用相应的方法
      addSidebarTab(tabData, isRight, insertIndex)

      // 关闭原标签页
      _pre_.browser.closeTabs([tab.id])

      console.log(`成功移动标签页到${sideText}边栏:`, { title: tab.title, url: tab.url })
    } catch (error) {
      console.error(`移动标签页到${sideText}边栏失败:`, error)
    }
  }

  // 通过tabid获取标签页
  function getTabById(tabId: number) {
    let type: 'left' | 'right' = 'left'
    let tab = data.leftTabs.find(t => t.origin.id === tabId)
    if (!tab) {
      tab = data.rightTabs.find(t => t.origin.id === tabId)
      type = 'right'
    }

    if (!tab) return null

    return {
      tab,
      type
    }
  }

  // 导出所有状态和方法
  const storeInstance = {
    // 状态
    leftTabs: computed(() => data.leftTabs),
    lastLeftActiveTabId: computed(() => lastLeftActiveTabId.value),
    rightTabs: computed(() => data.rightTabs),
    rightTempTabs: computed(() => data.rightTempTabs),
    rightActiveIds: computed(() => data.rightActiveIds),
    separateOpenIds: computed(() => data.separateOpenIds),
    currentSidebars,
    moveTabToSidebar,
    getTabById,
    setActiveTab,

    // 左边栏方法
    addSidebarTab,
    removeLeftTab,
    moveSidebarTab,
    findLeftTab,
    isLeftTab,

    // 右边栏方法
    removeRightTab,
    openRightTempTab,
    isRightTab,
    moveSidebarTabAcrossSides
  }

  // 仅在 E2E 环境将 sidebarStore 暴露到全局（用于测试）
  // @ts-ignore
  if (globalThis._pre_ && _pre_.isE2E) {
    // @ts-ignore
    ;(globalThis as any).sidebarStore = storeInstance
  }

  return storeInstance
})
